package com.mxpio.erp.quality.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.quality.entity.VPurchaseReceipt;
import com.mxpio.erp.common.quality.service.VPurchaseReceiptService;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.quality.entity.InQualityOrder;
import com.mxpio.erp.common.quality.entity.InQualityOrderLine;
import com.mxpio.erp.common.quality.service.InQualityOrderLineService;
import com.mxpio.erp.common.quality.service.InQualityOrderService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.quality.policy.DefaultInQualityOrderNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "InQualityOrderController", description = "入库验收单接口")
@RestController
@RequestMapping("/erp/quality/qo/")
public class InQualityOrderController {
	
	@Autowired
	private InQualityOrderService inQualityOrderSerivce;
	
	@Autowired
	private InQualityOrderLineService inQualityOrderLineSerivce;
	
	@Autowired
	private NoticeService noticeService;

	@Autowired
	private VPurchaseReceiptService vPurchaseReceiptService;

	@GetMapping("list")
	@Operation(summary = "入库验收单列表", description = "获取入库验收单列表", method = "GET")
	public Result<List<InQualityOrder>> list(Criteria criteria) throws UnsupportedEncodingException {
		List<InQualityOrder> tos = inQualityOrderSerivce.list(InQualityOrder.class, criteria);
		return Result.OK(tos);
	}
	
	@GetMapping("page")
	@Operation(summary = "入库验收单列表(分页)", description = "获取入库验收单列表(分页)", method = "GET")
	public Result<Page<InQualityOrder>> page(Criteria criteria, Integer pageSize, Integer pageNo) throws UnsupportedEncodingException {
		Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
		Page<InQualityOrder> page = inQualityOrderSerivce.listPage(InQualityOrder.class, pageAble, criteria);
		return Result.OK(page);
	}
	
	@GetMapping("list/{noticeNo}")
	@Operation(summary = "根据noticeNo获取入库验收单", description = "根据noticeNo获取入库验收单", method = "GET")
	public Result<InQualityOrder> getById(@PathVariable(name = "noticeNo", required = true) String noticeNo) {
		InQualityOrder inQualityOrder = inQualityOrderSerivce.getById(InQualityOrder.class, noticeNo);
		return Result.OK(inQualityOrder);
	}
	
	@RequestMapping("save")
    @Operation(summary = "保存入库验收单", description = "保存入库验收单")
    public Result<InQualityOrder> save(@RequestBody InQualityOrder inQualityOrder) {
		inQualityOrderSerivce.save(inQualityOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof InQualityOrderLine){
        			InQualityOrder inQualityOrder = context.getParent();
                    ((InQualityOrderLine) o).setNoticeNo(inQualityOrder.getNoticeNo());
        		}
        		return true;
        	}
        });
        return Result.OK(inQualityOrder);
    }
	
	@DeleteMapping("remove/{noticeNos}")
	@Operation(summary = "删除入库验收单", description = "删除入库验收单", method = "DELETE")
	public Result<InQualityOrder> remove(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
		String noticeNo[] = noticeNos.split(",");
		for(String key : noticeNo){
			Criteria c = Criteria.create().addCriterion("noticeNo", Operator.EQ, key);
			inQualityOrderLineSerivce.removeBatch(InQualityOrderLine.class, c);
			inQualityOrderSerivce.delete(InQualityOrder.class, key);
		}
		return Result.OK();
	}
	
    @PutMapping("submit/{noticeNo}")
    @Operation(summary = "提交入库验收单", description = "提交入库验收单", method = "PUT")
    public Result<Object> submit(@PathVariable(name = "noticeNo", required = true) String noticeNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	InQualityOrder notice = inQualityOrderSerivce.getById(InQualityOrder.class, noticeNo);
		if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
			return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
		}
    	NoticeContext context = noticeService.execute(notice, new DefaultInQualityOrderNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }

	@GetMapping("listbynos/{noticeNos}")
	@Operation(summary = "根据noticeNos获取对应入库验收单及明细", description = "根据noticeNos获取入库验收单及明细", method = "GET")
	public Result<List<InQualityOrder>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
		return inQualityOrderSerivce.listByIds(noticeNos);
	}

	@PutMapping("reject/{noticeNo}")
	@Operation(summary = "拒绝入库验收单", description = "拒绝入库验收单", method = "PUT")
	public Result<? extends Notice> close(@Parameter(description="入库验收单单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
		/*InQualityOrder notice = inQualityOrderSerivce.getById(InQualityOrder.class,noticeNo);
		return noticeService.updateNoticeStatus(notice, NoticeStatusEnums.NoticeStatus.REJECT);*/
		return inQualityOrderSerivce.reject(noticeNo);
	}
	@GetMapping("confirmed/vpage")
	@Operation(summary = "采购到货(已确认入库验收)报表-分页 ", description = "采购到货(已确认入库验收)报表-分页 ", method = "GET")
	public Result<Page<VPurchaseReceipt>> getUnqualifiedDisposal(Criteria criteria, Integer pageSize, Integer pageNo) {
		Pageable pageAble = PageRequest.of(pageNo-1, pageSize);
		Page<VPurchaseReceipt> page = vPurchaseReceiptService.listPage(pageAble, criteria);
		return Result.OK(page);
	}
}
